package com.dx.weichat.weichat.controller;

import com.dx.weichat.weichat.service.WXMessageHandleService;
import com.dx.weichat.weichat.wechatUtils.SHA1;
import com.dx.weichat.weichat.wechatUtils.WSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: dx
 * @date: 2018/10/6/0006
 * @description:微信验证的controller
 */
@RequestMapping("/weChat")
@Controller
public class WeChatVerify {
    private static Logger logger = LoggerFactory.getLogger(WeChatVerify.class);
	@Value("${wechat.token}")
	private String token;
	@Autowired
	private WXMessageHandleService wxMessageHandleService;
	@Autowired
	private RestTemplate restTemplate;

	/**
	 * @author:dx
	 * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	 * @param timestamp 时间戳
	 * @param nonce 随机数
	 * @param echostr 随机字符串
	 *  若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
	 *  验证完地址后微信与本服务器的交互全都是与当前这个url
	@ResponseBody
	@RequestMapping("/verify")
	public String verify(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr){
		//1）将token、timestamp、nonce三个参数进行字典序排序
		//2）将三个参数字符串拼接成一个字符串进行sha1加密
		//3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		String signStr= SHA1.getSha1(token, timestamp, nonce);
		if(signature.equals(signStr)){
			return echostr;          // 验证成功返回原echostr内容
		}else{
			return "fail";
		}
	}*/
	@ResponseBody
	@RequestMapping("/wxExchange")
	public String verify(String signature,String timestamp, String nonce,String echostr,HttpServletRequest request, HttpServletResponse response){
		//当与微信交互时 微信传过来的echostr参数为空 故用此参数校验是否是验证微信的请求
		if(!StringUtils.isEmpty(echostr)){
			logger.info("=========================>开始微信验证<======================");
			//验证微信地址
			String signStr= SHA1.getSha1(token, timestamp, nonce);
			if(signature.equals(signStr))
				return echostr;          // 验证成功返回原echostr内容
			else
				return "fail";
		}else {
			//真正微信公众号交互的处理方式
			return wxMessageHandleService.handleMessage(request, response);
		}
	}

	@ResponseBody
	@RequestMapping("/getWeather")
	public String getWeather(@RequestParam String theCityCode){
		return WSUtil.getWeatherInfo(theCityCode);
	}
}
